package press.xiang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import press.xiang.constant.CommodityConstants;
import press.xiang.entity.Commodity;
import press.xiang.entity.Store;
import press.xiang.service.ICommodityService;
import press.xiang.service.IStoreService;

import java.util.List;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("commodity")
@AllArgsConstructor
@Slf4j
public class CommodityController {

    private final ICommodityService commodityService;
    private final IStoreService storeService;

    @GetMapping("query")
    public R query(){
        return R.ok(new Commodity().selectAll());
    }

    @PostMapping("save")
    public R save(@RequestBody Commodity commodity){
        if (StringUtils.isEmpty(commodity.getId())){
            commodity.setId(UUID.randomUUID().toString());
        }
        return R.ok(commodity.insert());
    }

    @PostMapping("update")
    public R update(@RequestBody Commodity commodity){
        commodity.updateById();
        return R.ok("success");
    }

    @PostMapping("delete")
    public R delete(@RequestBody Commodity commodity){
        commodity.deleteById();
        return R.ok("success");
    }


    @PostMapping("truncate-commodity")
    public R truncateCommodity(){
        commodityService.truncateCommodity();
        return R.ok("success");
    }

    /**
     * @description: 根据仓库类型生成商品
     * @param type 仓库类型，如果不给，表示给所有类型仓库增加商品
     * @return: com.baomidou.mybatisplus.extension.api.R
     * @author xiang
     * @date: 2022/4/22 1:32 下午
     */
    @PostMapping("create-random-commodity-by-type")
    public R createRandomCommodity(String type){
        Random r = new Random();
        LambdaQueryWrapper<Store> eq = Wrappers.<Store>query().lambda()
                .eq(Store::getType,type);
        List<Store> list = storeService.list(eq);
        list.forEach(s ->{
            // 商品个数
            int count = r.nextInt(5)+1;
            for (int i = 0; i < count; i++) {
                Commodity commodity = new Commodity();
                commodity.setId(String.valueOf(UUID.randomUUID()));
                String commodityName = CommodityConstants.map.get(i+1);
                commodity.setName(commodityName);
                commodity.setType(type);
                commodity.setStoreId(s.getId());
                // 商品数量（每个商品的数量）
                int total = r.nextInt(100);
                commodity.setTotal((double) total);
                commodity.insert();
            }
        });
        return R.ok("success");
    }

}
